﻿using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using PetaPoco;
using PmSoft;
using PmSoft.ApplicationContext;
using PmSoft.DBContext;
using PmSoft.Repositories;
using PmSoft.Utilities;

namespace Modules.System.Flow
{
    [UseDI(ServiceLifetime.Scoped)]
    public class SysFlowRepository : Repository<SysFlow, DefaultDbContext>
    {
        private readonly ILogger logger;

        public SysFlowRepository(DefaultDbContext dbContext, IApplicationContext applicationContext, ILogger<SysFlowRepository> logger)
            : base(dbContext, applicationContext)
        {
            this.logger = logger;
        }

        public IPagedList<SysFlow> GetFlows(FlowQuery query, int pageIndex, int pageSize)
        {
            Sql sql = Sql.Builder;
            sql.Select("id")
                .From("sys_flow");
            if (!string.IsNullOrEmpty(query.Keywords))
                sql.Where("(name Like @0 or code like @0)", "%" + StringUtility.StripSQLInjection(query.Keywords) + "%");

            sql.Where("is_deleted=0");
            sql.OrderBy("create_time DESC");
            return GetPagingEntities(pageSize, pageIndex, sql);
        }

        public bool Exists(SysFlow flow, int? id)
        {
            if (id.HasValue)
                return DbContext.Exists<SysFlow>("code=@0 and is_deleted=0 and id!=@1", flow.Code, id);
            return DbContext.Exists<SysFlow>("code=@0 and is_deleted=0", flow.Code);
        }

        public SysFlow? GetFlowByCode(string code)
        {
            Sql sql = Sql.Builder.Select("id").From("sys_flow").Where("code=@0", code);
            var id = DbContext.FirstOrDefault<int>(sql);
            if (id == 0)
                return null;
            return Get(id);
        }
    }
}